package com.me.model.normal;

import com.me.model.Item;

/**
 * @author 吕旺平
 * @date 2019/10/15 00:41:36
 * @description
 */
public class NormalItem extends Item {
	
	public NormalItem() {
	}
	
	public NormalItem(String title, String[] contents, int score, String answer) {
		super(title, contents, score, answer);
	}
	
	public NormalItem(String title, String[] contents, int score, String answer, boolean multiple) {
		super(title, contents, score, answer, multiple);
	}
	
	@Deprecated
	public NormalItem(int id, String title, String[] contents, int score, int answerId, boolean multiple) {
		super(id, title, contents, score, answerId, multiple);
	}
	
	@Deprecated
	public NormalItem(int id, String title, String[] contents, int score, String answer, boolean multiple) {
		super(id, title, contents, score, answer, multiple);
	}
	
	@Override
	public void setContent(String content){
		this.contents = content.substring(1,content.length() - 1).split(",");
	}
	
	@Override
	public String getTitle(int id){
		return String.format("第%d题：%s",id + 1,title);
	}
	
	@Override
	public boolean isRight() {
		return chooseId == answerId;
	}
	
	@Override
	public int getValue(int id) {
		int value;
		if (multiple) {
			value = (int) Math.pow(2, id);
		} else {
			value = id;
		}
		return value;
	}
	
	@Override
	public boolean isChecked(int id) {
		if (chooseId < 0 || id < 0) {
			return false;
		}
		if (multiple) {
			int rest = chooseId;
			while(true){
				int cId = log2(rest);
				if (id == cId){
					return true;
				}
				rest -= (int)Math.pow(2,cId);
				if (cId <= id) {
					break;
				}
			}
		} else {
			if (id == chooseId) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public int getChooseItemCount(){
		return contents.length;
	}
	
	@Override
	public String getChooseItemDescribe(int id){
		if (id >= contents.length) {
			return "获取选项错误，请联系管理员";
		}
		return String.format("%c.%s",(char)(id + 65),contents[id]);
	}

	@Override
	public String getAllChooseItemDescribe() {
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < contents.length; i++) {
			sb.append(getChooseItemDescribe(i));
			sb.append(" ");
		}
		return sb.toString();
	}

	@Override
	public void setAnswer(String answer) {
		if (multiple || answer.length() > 1){
			this.multiple = true;
			for (int c : answer.toLowerCase().toCharArray()) {
				answerId += Math.pow(2,c - 97);
			}
		}else{
			answerId = answer.toLowerCase().toCharArray()[0] - 97;
		}
	}
	
	@Override
	public String getAnswer() {
		StringBuilder sb = new StringBuilder();
		int aId = answerId;
		do {
			int choice = log2(aId);
			sb.append((char) (choice + 65));
			aId -= Math.pow(2,choice);
			if (aId <= 0) break;
		}while (true);
		
		return sb.toString();
	}
	
	private int log2(double n){
		return (int)Math.floor(Math.log(n)/Math.log(2));
	}
}
